﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI;
using Cwing.UI.Validation.Manager;

namespace Cwing.UI.Validation
{
    internal class ScriptManager
    {
        static ScriptManager _instance;

        private ScriptManager()
        {
        }

        public static ScriptManager Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new ScriptManager();
                }
                return _instance;
            }
        }

        public void RendScriptLib(Page page)
        {
            page.ClientScript.RegisterClientScriptResource(typeof(PageValidationManager), "Cwing.UI.Validation.js");
        }

        public void RendInital(Page page)
        {
            StringBuilder builder = new StringBuilder(512);
            builder.AppendFormat("CW.MandatoryMessage=\"{0}\";\r\n", ValidationConfigHelper.MandatoryMessage());
            builder.AppendFormat("CW.MandatoryColor=\"{0}\";\r\n", ValidationConfigHelper.section == null ? "#FFC030" : ValidationConfigHelper.section.MandatoryColor);
            builder.AppendFormat("CW.FailureColor=\"{0}\";\r\n", ValidationConfigHelper.section == null ? "#C03000" : ValidationConfigHelper.section.FailureColor);
            builder.Append("CW.Validation.Initial();\r\n");
            page.ClientScript.RegisterStartupScript(typeof(PageValidationManager), "Validation_Initial", builder.ToString(), true);
        }

        public void RendData(Page page, List<IValidation> ValidationControls)
        {
            StringBuilder builder = new StringBuilder(1024);
            StringBuilder keyBuilder = new StringBuilder(1024);
            for (int i = 0; i < ValidationControls.Count; i++)
            {
                if (ValidationControls[i].ValidationType != ValidationType.Server && ValidationControls[i].ValidationConfiguration != null)
                {
                    String script = ValidationControls[i].ToClientScript();
                    if (!String.IsNullOrEmpty(script))
                    {
                        builder.AppendFormat("CW.Add({0});\r\n", script);
                        keyBuilder.Append(ValidationControls[i].Self.ClientID);
                    }
                }
            }
            page.ClientScript.RegisterStartupScript(typeof(PageValidationManager), keyBuilder.ToString(), builder.ToString(), true);
        }

        public void Rend(Page page, List<IValidation> ValidationControls)
        {
            RendScriptLib(page);

            RendData(page, ValidationControls);
        }
    }
}
